package com.example.busquerysystem.fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.search.busline.BusLineResult;
import com.baidu.mapapi.search.busline.BusLineSearch;
import com.baidu.mapapi.search.busline.BusLineSearchOption;
import com.baidu.mapapi.search.busline.OnGetBusLineSearchResultListener;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.example.busquerysystem.R;
import com.example.busquerysystem.overlay.BusLineOverlay;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 公交线路查询
 */
public class LineFragment extends Fragment {

    //布局里面的控件
    private EditText cityet;
    private EditText busLineEt;
    private Button searchBtn;
    private Button nextLineBtn;

    //百度地图
    private TextureMapView bmapView;
    private BaiduMap bdMap;

    private String city;// 城市
    private String busLine;// 公交线路
    private List<String> buslineIdList; // 存储公交线路的id，以便于查询下一条线路
    private int buslineIndex = 0; //标记是第几个线路了

    private PoiSearch poiSearch;
    private BusLineSearch busLineSearch;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        SDKInitializer.initialize(getActivity().getApplicationContext());
        View line = inflater.inflate(R.layout.activity_line, container, false);
//        initView();
        return line;
    }

    public void onStart() {
        super.onStart();
        SDKInitializer.initialize(getActivity().getApplicationContext());
        initView();
    }

    private void initView() {
        bmapView = getView().findViewById(R.id.bmapView);
        bmapView.showZoomControls(false);
        bdMap = bmapView.getMap();

        cityet = getView().findViewById(R.id.city_et);
        busLineEt = getView().findViewById(R.id.busLine_et);
        searchBtn = getView().findViewById(R.id.busLine_search_btn);

        //分别写开始查询按钮和下一条查询按钮
        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                city = cityet.getText().toString().trim();
                busLine = busLineEt.getText().toString().trim();
                poiSearch.searchInCity((new PoiCitySearchOption())
                        .city(city)
                        .keyword(busLine));
            }
        });

        buslineIdList = new ArrayList<String>();
        //poi检索结果回调
        poiSearch = PoiSearch.newInstance();
        poiSearch.setOnGetPoiSearchResultListener(poiSearchResultListener);

        //公交线路信息结果
        busLineSearch = BusLineSearch.newInstance();
        busLineSearch.setOnGetBusLineSearchResultListener(busLineSearchResultListener);
    }

    /**
     * 查询线路
     */
    private void searchBusLine() {
        if (buslineIndex >= buslineIdList.size()) {
            buslineIndex = 0;
        }
        if (buslineIndex >= 0
                && buslineIndex < buslineIdList.size() && buslineIdList.size() > 0) {
            boolean flag = busLineSearch.searchBusLine((new BusLineSearchOption()).city(city)
                    .uid(buslineIdList.get(buslineIndex)));
            if (flag) {
                Toast.makeText(getActivity(), "检索成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(getActivity(), "检索失败", Toast.LENGTH_SHORT).show();
            }
            buslineIndex++;
        }
    }

    /**
     * Poi检索结果监视器
     */
    OnGetPoiSearchResultListener poiSearchResultListener = new OnGetPoiSearchResultListener() {
        @Override
        public void onGetPoiResult(PoiResult poiResult) {
            if (poiResult == null
                    || poiResult.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {// 没有找到检索结果
                Toast.makeText(getActivity(), "未找到结果",
                        Toast.LENGTH_LONG).show();

                return;
            }

            if (poiResult.error == SearchResult.ERRORNO.NO_ERROR) {// 检索结果正常返回
                // 遍历所有poi，找到类型为公交线路的poi
                bdMap.clear();
                buslineIdList.clear();

                for (PoiInfo poi : poiResult.getAllPoi()) {
//                    Toast.makeText(getActivity(), "POI", Toast.LENGTH_SHORT).show();
                    if (poi.type == PoiInfo.POITYPE.BUS_LINE
                            || poi.type == PoiInfo.POITYPE.SUBWAY_LINE) {
                        buslineIdList.add(poi.uid);
                    }
                }
                searchBusLine();
            }
        }

        @Override
        public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

        }

        @Override
        public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

        }
    };

    /**
     * 公交信息结果监听
     */
    OnGetBusLineSearchResultListener busLineSearchResultListener = new OnGetBusLineSearchResultListener() {
        @Override
        public void onGetBusLineResult(BusLineResult busLineResult) {
            if (busLineResult.error != SearchResult.ERRORNO.NO_ERROR) {
                Toast.makeText(getActivity(), "未找到结果", Toast.LENGTH_SHORT).show();
            } else {
                bdMap.clear();
                //BusLineOverlay
                BusLineOverlay overlay = new MyBuslineOverlay(bdMap);
                overlay.setData(busLineResult);
                overlay.addToMap();// 讲overlay放在地图上
                overlay.zoomToSpan();//缩放地图，使所有overlay都在合适的视野范围内
                bdMap.setOnMarkerClickListener(overlay);
                bmapView.invalidate();
                //公交线路名称
                List<BusLineResult.BusStation> list = new ArrayList<BusLineResult.BusStation>();
                try {
                    Toast.makeText(getActivity(), list.get(0).toString()+"", Toast.LENGTH_SHORT).show();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

        }
    };

    class MyBuslineOverlay extends BusLineOverlay {

        /**
         * 构造函数
         *
         * @param baiduMap 该BusLineOverlay所引用的 BaiduMap 对象
         */
        public MyBuslineOverlay(BaiduMap baiduMap) {
            super(baiduMap);
        }

        /**
         * 站点点击事件
         */
        @Override
        public boolean onBusStationClick(int index) {
            MarkerOptions options = (MarkerOptions) getOverlayOptions().get(index);
            bdMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(options.getPosition()));
            return true;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        bmapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        bmapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        poiSearch.destroy();// 释放检索对象资源
        busLineSearch.destroy();// 释放检索对象资源
        bmapView.onDestroy();
    }

}
